<?php
declare(strict_types=1);
namespace EasySMS\Gateways;

use EasySms\Traits\HasHttpRequest;
use Exception;

class IhuyiGateway extends Gateway
{
    use HasHttpRequest;

    const ENDPOINT_URL = 'http://106.ihuyi.com/webservice/sms.php?method=Submit';

    const ENDPOINT_FORMAT = 'json';

    const SUCCESS_CODE = 2;

    /**
     * @param  $to
     * @param  $message
     * @param Config $config
     *
     * @return array
     * @throws Exception
     */
    public function send($to, $message, Config $config): array
    {
        $params = [
            'account' => $config->get('api_id'),
            'mobile' => $to,
            'content' => $message,
            'time' => time(),
            'format' => self::ENDPOINT_FORMAT,
            'sign' => $config->get('signature'),
        ];

        $params['password'] = $this->generateSign($params);

        $result = $this->post(self::ENDPOINT_URL, $params);

        if (self::SUCCESS_CODE != $result['code']) {
            throw new Exception($result['msg'], $result['code'], $result);
        }

        return $result;
    }

    /**
     * Generate Sign.
     *
     * @param array $params
     *
     * @return string
     */
    protected function generateSign(array $params): string
    {
        return md5($params['account'].$this->config->get('api_key').$params['mobile'].$params['content'].$params['time']);
    }
}
